package com.ferry.transport.netty.cluster;

import com.ferry.transport.netty.consumer.Connector;
import com.ferry.transport.netty.future.future.InvokeFuture;
import com.ferry.transport.netty.lb.LoadBalancer;
import com.ferry.transport.netty.provider.DefaultProviderProcessor;
import com.ferry.transport.netty.provider.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by daiyong
 */
public class FailOverClusterInvoker extends AbstractClusterInvoker {

	private static final Logger logger = LoggerFactory.getLogger(FailOverClusterInvoker.class);

	private int retries;

	public FailOverClusterInvoker(LoadBalancer loadBalancer, Connector connector, int retries) {
		super(loadBalancer, connector);
		this.retries = retries;
	}

	@Override
	public InvokeFuture invoke(Request request) {

		InvokeFuture invokeFuture = null;

		for (int i = 0; i < retries; i++) {
			try {
				invokeFuture = write(request);

				if (null != invokeFuture) {
					return invokeFuture;
				}

			} catch (Exception e) {
				logger.warn("FailOverClusterInvoker write Exception, request:{}", request, e);
			}
		}

		throw new RuntimeException("FailOverClusterInvoker exception");
	}
}
